<?php
namespace Assistant\Model;
use IDCU\Model\RelationModel;

class ExpenseModel extends RelationModel
{
    protected $_validate = array(
        array('money','/^(([1-9]\d*)|0)(\.\d{1,2})?$/','请填写正确的金额',0,'regex',3),
    );

    protected $_link = array(
            'Community' => array(
            'mapping_type' => self::BELONGS_TO,
            'class_name' => 'Community',
            'mapping_name' => 'community',
            'foreign_key' => 'community_id'
            ),
            'Zone' => array(
                'mapping_type' => self::BELONGS_TO,
                'class_name' => 'Zone',
                'mapping_name' => 'zone',
                'foreign_key' => 'zone_id'
            ),
            'Building' => array(
                'mapping_type' => self::BELONGS_TO,
                'class_name' => 'Building',
                'mapping_name' => 'building',
                'foreign_key' => 'building_id'
            ),
            'Unit' => array(
                'mapping_type' => self::BELONGS_TO,
                'class_name' => 'Unit',
                'mapping_name' => 'unit',
                'foreign_key' => 'unit_id'
            ),

            'Room' => array(
                'mapping_type' => self::BELONGS_TO,
                'class_name' => 'Room',
                'mapping_name' => 'Room',
                'foreign_key' => 'room_id'
            )
       );

//    public function postExpense($room_id, $status)
//    {
//        $where['room_id'] = $room_id;
//        $where['status'] = $status;
//        $_data = $this->where($where)->select();
//        $data = array();
//        foreach ($_data as $k=>$v){
//            $data['totalmoney'] += $v['money'];
//        }
//        $data['room_id'] = $_data[0]['room_id'];
//        $data['room_name'] = $_data[0]['room_name'];
//        $data['status'] = $status;
//        $data['pay_time'] = time();
//        $data['typeTitle'] = getDicName('expenseType', $data['type']);
//        $url = 'http://smart.wx91go.com/index.php?g=Home&m=Index&a=HouseCharge';
//        apiPost($url, $data);
//    }

    public function roomSearch($pageSize = 10) {
         $uid = session('authId');
         $community_id = I('community_id');
         if(!$community_id)
             $community_id = getCommunityId($uid);
         if(!$community_id)
            return false;
         $zone_id = I('param.zone_id');
         $building_id = I('param.building_id');
         $unit_id = I('param.unit_id');
         $room_id = I('param.room_id');
         $is_edit = I('param.is_edit');
         $key = I('param.key');
         $where = array();
         $where['status'] = 1;
         if($key){
            if(preg_match("/^\d+$/", $key)) {
                $map['householder_mobi'] = array('like', "%$key%");
                $map['name'] = array('like', "%$key%");
            }else {
                 $map['householder_name'] = array('like', "%$key%");
                 $map['name'] = array('like', "%$key%");
                 $map['full_parent_name'] = array('like', "%$key%");
             }
         }
         if($community_id)
             $where['community_id'] = array('in',$community_id);
         if($zone_id)
             $where['zone_id'] = $zone_id;
         if($building_id)
             $where['building_id'] = $building_id;
         if($unit_id)
             $where['unit_id'] = $unit_id;
         if($room_id)
             $where['id'] = $room_id;
         if($is_edit)
             $where['is_edit'] = $is_edit;
        if($map){
            $map['_logic'] = 'OR';
            $where['_complex'] = $map;
        }
         /************************************* 翻页 ****************************************/
         $count = M('Room')->where($where)->count();
         $page = new \ZL\Page($count, $pageSize);
         $data['page'] = $page->show();
         /************************************** 取数据 ******************************************/
         $roomData = M('Room')->where($where)->limit($page->limit.','.$page->listRows)->select();
         $data['data'] = $roomData;
         return $data;
    }

    public function notPay($type=false){
        $communityData = M('Community')->where(array('children_count'=>array('neq',0)))->select();
        $data = array();
        foreach ($communityData as $c) {
            $where = array();
            if($type)
                $where['type'] = $type;
            $where['community_id'] = $c['id'];
            $where['status'] = 0;
            $expenseData = $this->where($where)->select();
            foreach ($expenseData as $v) {
                $data["未交总金额"] += $v['money'];
                $data[$c['name']] += $v['money'];
            }
        }


        return $data;
    }

    public function expenseSearch($pageSize = 10, $isAll=false, $is_edit=false, $status=false, $relation=true) {
        $community_id = I('community_id');
        if(!$isAll) {
            $uid = session('authId');
            if (!$community_id)
                $community_id = getCommunityId($uid);
            if (!$community_id)
                return false;
        }
         $zone_id = I('param.zone_id');
         $building_id = I('param.building_id');
         $unit_id = I('param.unit_id');
         $room_id = I('param.room_id');
         $year = I('param.year');
         $status = is_numeric($status)?$status:I('param.status');
         $is_edit = is_numeric($is_edit)?$is_edit:I('param.is_edit');
         $key = I('param.key');
         $where = array();
         if($key){
            if(preg_match("/^\d+$/", $key))
                 $where['payer_phone'] = array('like',"%$key%");
             else
                 $where['payer_name'] = array('like',"%$key%");
         }
         if($community_id && $community_id!='null')
             $where['community_id'] = array('in',$community_id);
         if($zone_id && $zone_id!='null')
             $where['zone_id'] = $zone_id;
         if($building_id && $building_id!='null')
             $where['building_id'] = $building_id;
         if($unit_id && $unit_id!='null')
             $where['unit_id'] = $unit_id;
         if($room_id && $room_id!='null')
             $where['id'] = $room_id;
         if($year && $year!='null')
             $where['year'] = $year;
         if(is_numeric($status))
             $where['status'] = $status;
         if(is_numeric($is_edit))
             $where['is_edit'] = $is_edit;
         /************************************* 翻页 ****************************************/
         $count = $this->where($where)->count();
         $page = new \ZL\Page($count, $pageSize);
         $data['page'] = $page->show();
         /************************************** 取数据 ******************************************/
         $expenseData = $this->where($where)->relation($relation)->limit($page->limit.','.$page->listRows)->select();
         $data['data'] = $expenseData;
//        myDump(I('param.'));
         return $data;
    }
    public function readRoom($pageSize = 10){
        $roomId = I('param.room_id');
        /************************************* 翻页 ****************************************/
        $count = $this->relation(true)->where(array('room_id'=>$roomId))->count();
        $page = new \ZL\Page($count, $pageSize);
        $data['page'] = $page->show();
        $data['data'] = $this->relation(true)->where(array('room_id'=>$roomId))->order('is_edit desc,status asc')->limit($page->limit.','.$page->listRows)->select();
        return $data;
    }
    public function readCommunity(){
        $roomId = I('param.room_id');
        $roomData =M('Room')->find($roomId);
        $data = M('Community')->where(array('id'=>$roomData['community_id']))->find();
        return $data;
    }

    public function getNo($room_id) {
        $no = $this->where(array('room_id'=>$room_id))->order('no desc')->find();
        if($no){
            $str = $no['no'];
            $str1 = substr($str,-4);
            $str1 = (int)$str1;
            $str1 = $str1+1;
            $str2 = substr($str,0,-4);
            return $str2.sprintf('%04s', $str1);
        }
        $data = M('Room')->where(array('id'=>$room_id))->find();
        return $data['no'].'0001';
    }

    //根据传入的key v 转变成中文解释
    public function kvToName($k,$v,$arr){
        if($no = strpos($k,'_id')){
            $data = substr($k,0,$no);
            $data = ucfirst($data);
            $data = M($data)->find($v)['name'];
            return $data;
        }
        if(strpos($k,'time') && $v){
            $data = date("Y-m-d",$v);
            return $data;
        }
        if($k=='type' && $v){
            $data = $arr['type'][$v];
            return $data;
        }
        if($k=='pay_way' && $v){
            $data = $arr['pay_way'][$v];
            return $data;
        }
        if($k=='status'){
            $data = $v==0?'未缴费':'已缴费';
            return $data;
        }
        return $v;
    }
    public function _before_write(&$data)
    {
        parent::_before_write($data); // TODO: Change the autogenerated stub
//        if($data['start_time'] && strpos($data['start_time'],'-'))
            $data['start_time'] = strtotime($data['start_time']);
//        if($data['end_time'] && strpos($data['end_time'],'-'))
            $data['end_time'] = strtotime($data['end_time']);
//        if($data['close_time'] && strpos($data['close_time'],'-'))
            $data['close_time'] = strtotime($data['close_time']);

        if($data['room_id']){
            $room = D('Admin/Room')->where(array('id'=>$data['room_id']))->find();
            $data['room_name'] = $room['full_parent_name'].$room['name'];
            $data['community_id'] = $room['community_id'];
            $data['zone_id'] = $room['zone_id'];
            $data['building_id'] = $room['building_id'];
            $data['unit_id'] = $room['unit_id'];
            if(!$data['no'])
                $data['no'] = $this->getNo($data['room_id']);
        }
    }

    public function _after_insert($data, $options)
    {
        parent::_after_insert($data, $options); // TODO: Change the autogenerated stub
    }

    public function _after_delete($data, $options)
    {
        parent::_after_delete($data, $options); // TODO: Change the autogenerated stub
        $data['id'] = $options['where']['id'];
        $url = 'http://smart.wx91go.com/index.php?g=Home&m=Index&a=delHouseCharge';
        apiPost($url, $data);
    }
}